package com.genesis.yunnanji.view;

import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.genesis.yunnanji.Constants;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.bean.BaseBean;
import com.genesis.yunnanji.bean.MessageEventBean;
import com.genesis.yunnanji.bean.UserInfoBean;
import com.genesis.yunnanji.utils.DateUtil;
import com.genesis.yunnanji.utils.NetUtils;
import com.genesis.yunnanji.widget.GlideCircleTransform;
import com.genesis.yunnanji.widget.PickerViewUtil;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.youth.xframe.utils.imageload.XImage;
import com.youth.xframe.widget.XToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.bining.footstone.utils.SharedUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 创建日期：2018/9/20 on 11:16
 * 作者:Kite
 * 描述:个人设置
 */
public class UserSettingActivity extends BaseActivity {

    @BindView(R.id.iv_head)
    ImageView ivHead;

    @BindView(R.id.tv_user_num)
    TextView tvUserNum;

    @BindView(R.id.tv_user_nickname)
    TextView tvUserNickname;

    @BindView(R.id.tv_user_gender)
    TextView tvUserGender;

    @BindView(R.id.tv_user_birthday)
    TextView tvUserBirthday;

    @BindView(R.id.tv_user_education)
    TextView tvUserEducation;

    @BindView(R.id.tv_user_profession)
    TextView tvUserProfession;

    @BindView(R.id.tv_user_address)
    TextView tvUserAddress;

    @BindView(R.id.tv_user_mobile)
    TextView tvUserMobile;

    @BindView(R.id.tv_user_email)
    TextView tvUserEmail;

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_setting;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("个人设置");
        getUserInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10001:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList == null || selectList.size() == 0) {
                        return;
                    }
                    String path = selectList.get(0).getCompressPath();
                    XImage.getInstance().load(ivHead, path, new GlideCircleTransform(this));
                    Log.e("LK", path + "");
                    Luban.with(this).load(path).setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                        }

                        @Override
                        public void onSuccess(File file) {
                            //uploadHeadIcon(file);
                        }

                        @Override
                        public void onError(Throwable e) {
                        }
                    }).launch();
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDataInfo(MessageEventBean messageEvent) {
        if (messageEvent.getType() == 0 || messageEvent.getType() == 2) {
            tvUserMobile.setText(messageEvent.getMessage());
        } else if (messageEvent.getType() == 1 || messageEvent.getType() == 3) {
            tvUserEmail.setText(messageEvent.getMessage());
        } else if (messageEvent.getType() == 5) {
            tvUserNickname.setText(messageEvent.getMessage());
        } else if (messageEvent.getType() == 7) {//地址
            tvUserAddress.setText(messageEvent.getMessage());
        }
    }

    @OnClick({R.id.user_head, R.id.user_num, R.id.user_nickname, R.id.user_gender, R.id.user_birthday, R.id.user_education,
            R.id.user_profession, R.id.user_address, R.id.user_mobile, R.id.user_email, R.id.change_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_head:
                initAvatar();
                break;
            case R.id.user_num:
                break;
            case R.id.user_nickname:
                advance(SetNicknameActivity.class, tvUserNickname.getText().toString());
                break;
            case R.id.user_gender:
                showGenderDialog();
                break;
            case R.id.user_birthday:
                PickerViewUtil.getInstance().showDatePicker(this);
                PickerViewUtil.getInstance().setOnTimeCompleteListener(new PickerViewUtil.OnTimeCompleteListener() {
                    @Override
                    public void onSelectDate(Date date) {
                        tvUserBirthday.setText(DateUtil.Date2String(date, "yyyy-MM-dd"));
                    }
                });
                break;
            case R.id.user_education:
                break;
            case R.id.user_profession:
                break;
            case R.id.user_address:
                advance(DeliveryAddressActivity.class, 1);
                break;
            case R.id.user_mobile:
                if (tvUserMobile.getText().toString().equals("")) {
                    advance(BindingActivity.class, 0);
                } else {
                    advance(BindingActivity.class, 2, tvUserMobile.getText().toString());
                }
                break;
            case R.id.user_email:
                if (tvUserEmail.getText().toString().equals("")) {
                    advance(BindingActivity.class, 1);
                } else {
                    advance(BindingActivity.class, 3, tvUserEmail.getText().toString());
                }
                break;
            case R.id.change_password:
                advance(BindingActivity.class, 4, "15213199211");
                break;
        }
    }

    /**
     * 修改头像
     */
    private void initAvatar() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                .theme(R.style.style_picture_white)//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量 int
                .minSelectNum(0)// 最小选择数量 int
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .previewVideo(false)// 是否可预览视频 true or false
                .enablePreviewAudio(false) // 是否可播放音频 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
//                .setOutputCameraPath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))// 自定义拍照保存路径,可不填
                .enableCrop(true)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                // .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                // .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                // .isGif()// 是否显示gif图片 true or false
//                .compressSavePath(FileUtils.getAppDefPath(FileUtils.PATH_IMAGE))//压缩图片保存地址
                .freeStyleCropEnabled(false)// 裁剪框是否可拖拽 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .openClickSound(false)// 是否开启点击声音 true or false
                // .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                // .previewEggs()// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                // .cropCompressQuality()// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                // .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                .scaleEnabled(true)// 裁剪是否可放大缩小图片 true or false
                // .videoQuality()// 视频录制质量 0 or 1 int
                //  .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
                // .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
                // .recordVideoSecond()//视频秒数录制 默认60s int
                .forResult(10001);//结果回调onActivityResult code
    }

    /**
     * 选择性别
     */
    private void showGenderDialog() {
        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_fragment_gender)
                .setScreenWidthAspect(UserSettingActivity.this, 0.96f)
                .setGravity(Gravity.BOTTOM)
                .setDialogAnimationRes(R.style.dialog_fragment_bottom_anim)
                .addOnClickListener(R.id.tv_male, R.id.tv_female, R.id.tv_cancel)
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, android.view.View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_male:
                                tvUserGender.setText("男");
                                tDialog.dismiss();
                                break;
                            case R.id.tv_female:
                                tvUserGender.setText("女");
                                tDialog.dismiss();
                                break;
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        JSONObject params = new JSONObject();
        try {
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.MEMBER_INDEX)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<UserInfoBean>, UserInfoBean>(new SimpleCallBack<UserInfoBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(UserInfoBean bean) {
                        tvUserNum.setText(bean.getMember().getUsername());
                        tvUserNickname.setText(bean.getMember().getNickname());
                        RequestOptions options = new RequestOptions()
                                .placeholder(R.drawable.comment_defaultphoto)
                                .error(R.drawable.comment_defaultphoto)
                                .fallback(R.drawable.comment_defaultphoto)
                                .transform(new GlideCircleTransform(UserSettingActivity.this));
                        Glide.with(UserSettingActivity.this)
                                .load(Constants.PIC_ADMIN + bean.getMember().getPhoto())
                                .apply(options)
                                .into(ivHead);
                        switch (bean.getMember().getSex()) {
                            case "0":
                                tvUserGender.setText("保密");
                                break;
                            case "1":
                                tvUserGender.setText("男");
                                break;
                            case "2":
                                tvUserGender.setText("女");
                                break;
                        }
                        tvUserBirthday.setText(bean.getMember().getBirthday());
                        tvUserAddress.setText("");
                    }
                }) {
                });
    }

}
